HTML5的新增元素 |
您所在的位置:网站首页 › html5 语法 › HTML5的新增元素 |
1. 定义 画布是用来绘制图形,属于html元素,是h5的新元素,需要结合js。 2. 语法
【注意:canvas需要写闭合标签,不可以以单标签的形式出现】 一般不建议使用css设置它的宽高 3. 属性width 默认值300px height 默认值150px 4. 方法 4.1 形状的方法 1.矩形fillRect(x,y,width,height):绘制一个填充的矩形图形 strokeRect(x,y,width,height):绘制一个边框的矩形图形 lineWidth:设置线的宽度 fillStyle:设置填充的颜色 strokeStyle:设置边框颜色 2.圆形ctx.arc(x,y,r,startAngle,endAngle,anticlockwise); x,y 指圆心 r 指半径 startAngle:开始的点 endAngle:结束的点,顺时针(逆时针) anticlockwise:默认顺时针 例子:奥运五环 圆形 var canvas = $("#canvas")[0]; //检查浏览器是否支持canvas //支持canvas if(canvas.getContext){ //配置画笔 var ctx = canvas.getContext("2d"); ctx.lineWidth=10; ctx.beginPath(); ctx.arc(100,100,60,0,2*Math.PI); ctx.strokeStyle='blue'; ctx.stroke(); ctx.beginPath(); ctx.arc(180,100,60,0,2*Math.PI); ctx.strokeStyle='black'; ctx.stroke(); ctx.beginPath(); ctx.arc(260,100,60,0,2*Math.PI); ctx.strokeStyle='red'; ctx.stroke(); ctx.beginPath(); ctx.arc(140,180,60,0,2*Math.PI); ctx.strokeStyle='yellow'; ctx.stroke(); ctx.beginPath(); ctx.arc(230,180,60,0,2*Math.PI); ctx.strokeStyle='green'; ctx.stroke(); }else{ alter("您的浏览器不支持canvas") } 3.线段ctx.beginPath(); 新建一条路径 ctx.closePath(); 闭合一条路径 fill() 填充路径的内容区域【使用fill的时候可以不用closePath】 stroke() 通过线条绘制图像轮廓【使用stroke的时候可以使用closePath】 moveTo(x,y) 将笔触移动到指定的坐标上 lineTo(x,y) 绘制直线 x,y是线结束的位置。 例子:五角星 五角星 var canvas=$("canvas")[0]; if(canvas.getContext){ var ctx=canvas.getContext("2d"); ctx.beginPath(); ctx.moveTo(100,100); ctx.lineTo(200,100); ctx.lineTo(130,180); ctx.lineTo(150,50); ctx.lineTo(180,180); ctx.lineTo(100,100); ctx.stroke(); }else{ alter("您的浏览器不支持canvas") } 4.2 颜色渐变 1.线性渐变createLinearGradient(前面两个参数是渐变起始的位置,后俩个参数是渐变结束的位置); 线性渐变 //写在头部,文档加载完毕执行代码 window.onload=function(){ //1.获取画布 var canvas=document.querySelector('canvas'); //2.获取上下文对象,获取画笔 var context=canvas.getContext("2d"); //3.声明一个线性渐变对象 .createLinearGradient(前面两个参数是渐变起始的位置,后俩个参数是渐变结束的位置); var g=context.createLinearGradient(0,0,400,400); //4.给渐变对象添加渐变色 g.addColorStop(0,"red"); g.addColorStop(0.5,"yellow"); g.addColorStop(1,"cyan"); //5.将渐变对象给到填充样式 context.fillStyle=g; //6.绘线性渐变矩形 context.fillRect(0,0,400,400); } 2.径向渐变.createRadialGradient(第一二个参数是里面小圆圆心,第三个参数是一个半径,第四五个参数是大圆的圆心,第六个参数是大圆的半径); 径向渐变 //写在头部,文档加载完毕执行代码 window.onload=function(){ //1.获取画布 var canvas=document.querySelector('canvas'); //2.获取上下文对象,获取画笔 var context=canvas.getContext("2d"); //3.声明一个径向渐变对象 .createRadialGradient(第一二个参数是里面小圆圆心,第三个参数是一个半径,第四五个参数是大圆的圆心,第六个参数是大圆的半径); var g=context.createRadialGradient(200,200,50,200,200,200); //4.给渐变对象添加渐变色 0-1 g.addColorStop(0,"red"); g.addColorStop(0.25,"pink"); g.addColorStop(0.5,"yellow"); g.addColorStop(0.75,"blue"); g.addColorStop(1,"cyan"); //5.将渐变对象给到填充样式 context.fillStyle=g; //6.绘线性渐变矩形 context.fillRect(0,0,400,400); } 5. 用画布画图的步骤1.获取画布 2.获取上下文对象context 3.绘制填充样式 4.绘制图形 |
今日新闻 |
推荐新闻 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |